//
//  MemoryChapterViewController.m
//  ExerciseOC
//
//  Created by 王子曦 on 2025/4/14.
//

#import "MemoryChapterViewController.h"
#import "Memory/ARCViewController.h"
#import "Memory/RetainCountViewController.h"
#import "Memory/CircularReferenceViewController.h"
#import "Memory/AutoReleasePoolViewController.h"
#import "Memory/WeakTableViewController.h"

@interface MemoryChapterViewController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *memoryTopics;
@end

@implementation MemoryChapterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"内存管理";
    
    // 初始化知识点数组
    self.memoryTopics = @[
        @{@"title": @"ARC", @"detail": @"自动引用计数机制", @"class": [ARCViewController class]},
        @{@"title": @"引用计数", @"detail": @"对象引用计数原理", @"class": [RetainCountViewController class]},
        @{@"title": @"循环引用", @"detail": @"内存泄漏问题及解决方案", @"class": [CircularReferenceViewController class]},
        @{@"title": @"自动释放池", @"detail": @"延迟释放机制", @"class": [AutoReleasePoolViewController class]},
        @{@"title": @"弱引用表", @"detail": @"weak指针管理机制", @"class": [WeakTableViewController class]}
    ];
    
    // 创建表格视图
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    // 注册单元格
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"MemoryCell"];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.memoryTopics.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MemoryCell" forIndexPath:indexPath];
    
    NSDictionary *topic = self.memoryTopics[indexPath.row];
    cell.textLabel.text = topic[@"title"];
    cell.detailTextLabel.text = topic[@"detail"];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *topic = self.memoryTopics[indexPath.row];
    Class viewControllerClass = topic[@"class"];
    UIViewController *detailVC = [[viewControllerClass alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
}

@end